// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

import MuseUI from 'muse-ui'
import 'muse-ui/dist/muse-ui.css'

import {
  Button,
  Select
} from 'muse-ui';
import axios from 'axios'
Vue.prototype.$http = axios;

import $ from 'jquery'
import md5 from 'js-md5';

import config from './config'

var ToastOption = {
  position: 'top', // 弹出的位置
  time: 2000, // 显示的时长
  closeIcon: 'close', // 关闭的图标
  close: true, // 是否显示关闭按钮
  successIcon: 'check_circle', // 成功信息图标
  infoIcon: 'info', // 信息信息图标
  warningIcon: 'priority_high', // 提醒信息图标
  errorIcon: 'warning' // 错误信息图标
}
import Toast from 'muse-ui-toast';
Vue.use(Toast, ToastOption);

import Message from 'muse-ui-message';
import 'muse-ui-message/dist/muse-ui-message.css';
Vue.use(Message);

Vue.config.productionTip = false

Vue.use(MuseUI)
Vue.use(Button);
Vue.use(Select);

import help from '@/libs/help'
Vue.use(help)
Vue.prototype.$help = help

/* eslint-disable no-new */
// rpc模块
let ab = {
  toJson(data) {
    return JSON.stringify(data)
  },
  args(args, off, len) {
    if (off == undefined) {
      return Array.prototype.slice.call(args)
    }

    if (len === undefined) {
      len = args.length
    }

    var ary = []
    for (; off < len; off++) {
      ary.push(args[off])
    }

    return ary
  },
}

// 应用编号和签名 demo测试使用， 所有开发接口代码 请不要在前端调用
let appId = 1
let appSecret = "l3A44xNwuZ8"

let ab_ = Vue.prototype.ab_ = {
  // 生成带签名的RpcUri
  sign(t) {
    console.log('?t=' + t + '&p=' + appId + '&s=' + md5(appSecret + ',' + t))
  },
  pr(uri) {
    var t = parseInt(new Date().getTime() / 1000)
    return uri + '?t=' + t + '&p=' + appId + '&s=' + md5(appSecret + ',' + t)
  },
  rq(uri, postData, callback, files, backgroud) {
    $.ajax({
      url: config.apiHost + uri,
      type: 'POST',
      dataType: 'json',
      data: postData,
      success: function(rep) {
        callback(undefined, rep)
      }
    })
  },
  rpc(type, uri, callback) {
    let len = arguments.length
    callback = arguments[len - 1]
    if (typeof(callback) === 'function') {
      let rpcRep = function(err, rep) {
        ab_.rpcRep(rep, callback)
      }

      if (len > 3) {
        ab_.rq(uri, ab.toJson(ab.args(arguments, 2, len - 1)), rpcRep, 0, type === 0)

      } else {
        ab_.rq(uri, 0, rpcRep, 0, type === 0)
      }

    } else {
      if (len === 4 && Array.isArray(callback)) {
        // 小程序arguments 最长9个兼容处理
        var call = arguments[2]
        if (typeof(call) === 'function') {
          ab_.rq(uri, ab.toJson(callback), function(err, rep) {
            ab_.rpcRep(rep, call)
          }, 0, type === 0)
          return
        }
      }

      let rpcRep = function(err, rep) {
        ab_.rpcRep(rep, 0)
      }

      if (len > 2) {
        ab_.rq(uri, ab.toJson(ab.args(arguments, 2, len)), rpcRep, 0, type === 0)

      } else {
        ab_.rq(uri, 0, rpcRep, 0, type === 0)
      }
    }
  },
  rpcRep(data, callback) {
    if (!data || !Array.isArray(data)) {
      callback('data err', undefined)
      return
    }

    try {
      if (data.length > 2) {
        //ab.posts(data, 2)
      }

    } finally {
      if (data[0] === 1) {
        if (callback) callback(undefined, data[1])

      } else {
        $root.$toast.error('请求错误, ' + data[0]);
        // 				let err = data[0]
        // 				if (err === 'NO_LOGIN') {
        // 					ab_.rqErr(err, data[1])
        // 					return
        // 				}
        //
        // 				try {
        // 					if (callback && callback(err, undefined, data[1])) {
        // 						return
        // 					}
        //
        // 				} catch (e) {
        // 					throw e
        // 				}
        //
        // 				ab_.rqErr(err, data[1])
      }
    }
  },

  //系统交互
}

let $root = global.$root = new Vue({
  el: '#app',
  router,
  components: {
    App
  },
  template: '<App/>',
  data: {
    token: '',
    pUser: {},
    err_: '',
    localIp: '',
    payedOrderId: '',
  },
  computed: {

  },
  created() {
    let self = this
    // 获取token
    this.token = this.$route.query.token
    // 自动登录
    this.autoLogin(true)
  },
  methods: {
    //返回上一页
    back() {
      if (window.history && window.history.length <= 1) {
        this.replace('/')

      } else {
        this.$router.back(-1)
      }
    },

    //一乙用户带上token信息，请求一乙平台O/oauth接口进行登录,若自动登录失败，则进入一乙互通的登录注册页面
    autoLogin(auto) {
      let self = this
      if (self.token) {
        ab_.rpc(1, ab_.pr('O/oauth'), self.token,
          function(err, res) {
            if (res) {
              // 自动登陆信息(这里也可以匹配会员信息（信任一乙平台信息），进行自动登录)
              if (res.pToken) {
                // 自动登录pToken
                self.pUser = {
                  username: res.pToken
                }
                self.$toast.success('自动登录成功！');
                return
              }
            }

            self.$toast.error('自动登录失败！');
          })
      } else if (!auto) {
        $postMessage('login')
      }
    },
    //应用授权回调，应用方登录内部登录成功后，需要同步一下授权证书给平台服务器
    pTokenBack(pToken) {
      let self = this
      ab_.rpc(1, ab_.pr('O/pToken'), self.token, pToken,
        function(err, res) {
          if (res) {
            // 登录同步
            self.$toast.success('登录同步成功！');
          }
        })
    },
    //支付接口
    pay(amount, name, desc) {
      var self = this
      if (!self.loginInfo) {
        $postMessage('login')
        return
      }

      ab_.rpc(1, ab_.pr('O/order'), {
        mmId: self.loginInfo.member.id,
        oId: new Date().getTime(),
        name: name,
        desc: desc,
        amount: amount,

      }, function(err, res) {
        // self.err_ += $postMessage
        // uni.navigateTo({
        // 	url: '/pages/transfer?t=pay,' + res
        // })
        if (res) {
          $postMessage('pay', res)
        }
      })
    },

    //个人中心接口，请求O/member接口
    profile() {
      var self = this
      if (!self.loginInfo) {
        $postMessage('login')
        return
      }
    },

    rpcCfg(_apiHost, _appId, _appSecret) {
      config.apiHost = _apiHost || config.apiHost
      appId = _appId || appId
      appSecret = _appSecret || appSecret
    },

    //对外提供调用测试
    rpcTest(uri, args, callback) {
      if (!Array.isArray(args)) {
        console.error('args must be array')
        return
      }

      ab_.rpc(1, ab_.pr(uri), callback || function(err, res) {
        if (err) {
          console.error(err)
        }

        console.log(res)
      }, args)
    },
  },
})

// 自定义消息处理
window.$onMessage = {
  login(v) {
    console.log('login at ' + v)
    $root.token = v
    var self = $root
    ab_.rpc(1, ab_.pr('O/member'), self.token, false,
      function(err, res) {
        if (res) {
          // 会员信息
          self.loginInfo = res;
        }
      })
  },
  onBackPress() {
    $root.$toast.error('获得了backPress！');
  },
}

uniReady(function() {
  console.log('uniRead1')
})

uniReady(function() {
  console.log('uniRead2')
})

uniReady(function() {
  console.log('uniRead3')
})

//uniConsole()
//get the IP addresses associated with an account
function getIPs(callback) {
  //compatibility for firefox and chrome
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new myPeerConnection({
      iceServers: []
    }),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function iterateIP(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }

  //create a bogus data channel
  pc.createDataChannel("");

  // create offer and set local description
  pc.createOffer().then(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(iterateIP);
    });

    pc.setLocalDescription(sdp, noop, noop);
  }).catch(function(reason) {
    // An error occurred, so handle the failure to connect
  });

  //sten for candidate events
  pc.onicecandidate = function(ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
  };
}

//Test: Print the IP addresses into the console
getIPs(function(ip) {
  console.log(ip);
});
